<template>
  <div v-loading="loading" class="score-query">
    <div class="query-container">
      <el-card class="query-form">
        <div class="control-box">
          <el-form
            ref="queryFormRef"
            :model="queryForm"
            :rules="rules"
            label-width="80px"
            class="horizontal-form form-small"
          >
            <el-form-item label="参赛项目">
              <el-select
                v-model="queryForm.projectType"
                placeholder="请选择参赛项目"
                @change="projectTypeChange"
              >
                <el-option value="" label="请选择参赛项目" disabled />
                <el-option
                  v-for="item in competitions"
                  :key="item.playType"
                  :value="item.key"
                  :label="item.title"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="组别" prop="groupCategory">
              <el-select
                v-model="queryForm.groupCategory"
                placeholder="请选择参赛组别"
                @change="groupCategoryChange"
              >
                <el-option label="小学组" value="小学组" />
                <el-option label="初中组" value="初中组" />
                <el-option label="高中组" value="高中组" />
              </el-select>
            </el-form-item>
            <el-form-item label="批次号">
              <el-select
                v-model="queryForm.batchNo"
                placeholder="请选择批次号"
                class="batch-no-select"
              >
                <el-option
                  v-for="(batch, index) in batchNoList"
                  :key="index"
                  :label="batch"
                  :value="batch"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="参赛编号" prop="regNo">
              <el-input
                v-model="queryForm.regNo"
                v-format.integer="{ grouping: false }"
                placeholder="请输入参赛编号"
                :prefix-icon="Document"
              />
            </el-form-item>
            <el-button
              type="primary"
              @click="handleQuery"
              class="query-button button-search"
              >查询成绩
            </el-button>
          </el-form>
        </div>

        <div class="match-tree-container" v-if="showMatchTree">
          <match-tree
            :editable="false"
            ref="matchTreeRef"
            :activeTab="queryForm.projectType"
            :playType="type"
            :batchNo="queryForm.batchNo"
            :groupCategory="queryForm.groupCategory"
          />
        </div>
        <div class="match-tree-container" v-else><el-empty /></div>
      </el-card>
    </div>
    <score-dialog
      v-model:dialogVisible="viewScoreDialogVisible"
      :row="scoreDialogParams"
      :type="queryForm.projectType"
      :playType="type"
    />
  </div>
  <CelebrationEffect
    v-model="showDialog"
    @handleColse="closeCelebrationEffect"
    :rank="currentRank"
  />
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { Document } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import matchTree from '@/components/matchTree.vue'
import scoreDialog from '@/components/scoreDialog.vue'
import useAppStore from '@/store/modules/app.js'
import { typeFieldMap } from '@/config/type.js'
import CelebrationEffect from '@/components/CelebrationEffect.vue'

const appStore = useAppStore()
const queryFormRef = ref(null)
const showMatchTree = ref(false)
const viewScoreDialogVisible = ref(false)

const competitions = computed(() => appStore.competitions)
import {
  droneApi,
  fireApi,
  gobangApi,
  obstacleApi,
  logisticsApi,
  infoApi,
} from '@/api/modules'

const type = computed(() => typeFieldMap[queryForm.projectType])
const scoreDialogParams = ref({})
const loading = ref(false)

const queryForm = reactive({
  regNo: '',
  projectType: 'logistics',
  batchNo: '',
  groupCategory: '小学组',
})
const apiHandle = {
  drone: droneApi,
  fire: fireApi,
  obstacle: obstacleApi,
  logistics: logisticsApi,
  gobang: gobangApi,
}

const rules = {
  regNo: [{ required: true, message: '请输入参赛编号', trigger: 'blur' }],
}

const matchTreeRef = ref(null)
const showDialog = ref(false)
//点击查询成绩
const handleQuery = () => {
  queryFormRef.value.validate(async (valid) => {
    if (valid) {
      const isLogisticsOrFire = ['logistics', 'fire'].includes(
        queryForm.projectType
      )
      if (isLogisticsOrFire) {
        showMatchTree.value = false
      }
      loading.value = true
      scoreDialogParams.value = {}
      const params = {
        batchNo: queryForm.batchNo,
        playType: typeFieldMap[queryForm.projectType],
        groupCategory: queryForm.groupCategory,
        regNo: queryForm.regNo,
      }
      const res = await apiHandle[queryForm.projectType].rank.post(params)
      loading.value = false
      if (res.code !== 200) {
        ElMessage.error(res.message || '获取数据失败')
        return
      }

      if (!isLogisticsOrFire) {
        const newParams = {
          groupCategory: queryForm.groupCategory,
          playType: typeFieldMap[queryForm.projectType],
          batchNo: queryForm.batchNo,
        }
        const res = await infoApi.competitionQuery.post(newParams)
        if (res.code !== 200) {
          ElMessage.error('获取数据失败')
          loading.value = false
          return
        }
        if (res.data.status === 'group') {
          showMatchTree.value = false
        } else {
          showMatchTree.value = true
          nextTick(() => {
            matchTreeRef.value.getTreeData()
          })
        }
      }

      scoreDialogParams.value = res.data || {}
      // 判断排名数字是否前三，前三显示庆祝效果
      if (scoreDialogParams.value.id === null) {
        ElMessage.error('未查询到该参赛编号')
        return
      }
      currentRank.value = res.data.scoreRank
      if (
        currentRank.value === null ||
        currentRank.value === '' ||
        currentRank.value === undefined
      ) {
        ElMessage.error('比赛尚未结束')
      }
      if (currentRank.value !== null && currentRank.value <= 3) {
        showDialog.value = true
      } else {
        viewScoreDialogVisible.value = true
      }
    } else {
      ElMessage.error('请填写参赛编号')
      return false
    }
  })
}

// 页面加载时添加一些随机动画延迟
onMounted(() => {
  // 为奖牌添加随机动画延迟
  const medals = document.querySelectorAll('.medal')
  medals.forEach((medal) => {
    const delay = Math.random() * 2
    medal.style.animationDelay = `${delay}s`
  })

  // 为粒子添加随机动画延迟
  const particles = document.querySelectorAll('.particle')
  particles.forEach((particle) => {
    const delay = Math.random() * 5
    particle.style.animationDelay = `${delay}s`
  })

  //调用获取批次号
  getCompetitionType()
})
const batchNoList = ref([])
//获取批次号
const getCompetitionType = async (params) => {
  const batchRes = await infoApi.getBatchNoList.post({
    playType: typeFieldMap[queryForm.projectType],
    groupCategory: queryForm.groupCategory, // 使用 .value 获取值
  })
  if (batchRes.code !== 200) {
    ElMessage.error(batchRes.message || '获取数据失败')
    return
  }
  batchNoList.value = [...new Set(batchRes.data || [])]
  queryForm.batchNo = batchRes.data[0] || ''
}
//比赛类型change事件
const projectTypeChange = (value) => {
  getCompetitionType()
}
//组别change事件
const groupCategoryChange = (value) => {
  getCompetitionType()
}

const currentRank = ref(0)
const closeCelebrationEffect = () => {
  showDialog.value = false
  //关闭庆祝弹框显示成绩详情框
  viewScoreDialogVisible.value = true
}
</script>

<style lang="scss" scoped>
.score-query {
  position: relative;
  overflow: hidden;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.query-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  gap: 20px;
  margin: 10px auto;
  max-width: 1200px;
  position: relative;
  z-index: 1;

  .control-box {
    display: flex;
    // justify-content: space-between;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 10px;
  }
  .query-form {
    width: 100%;
    border-radius: 12px;
    overflow: hidden;
    padding: 0;
    .match-tree {
      padding: 0 10px;
    }
    .match-tree-container {
      margin-top: 20px;
      height: calc(100vh - 235px);
      overflow-y: auto;
      :deep canvas {
        margin-bottom: 0;
      }
    }
    .right-button {
      margin-left: 20px;
    }
    .horizontal-form {
      display: flex;
      align-items: center;
      justify-content: left;
      gap: 20px;

      .el-form-item {
        width: 200px;
        margin-bottom: 0;

        :deep .el-form-item__label {
          width: auto !important;
        }
      }
      .query-button {
        position: relative;
        overflow: hidden;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 5px 15px rgba(64, 158, 255, 0.3);

          .button-effect {
            transform: scale(1.5);
            opacity: 0;
          }
        }

        .button-effect {
          position: absolute;
          top: 50%;
          left: 50%;
          width: 100%;
          height: 100%;
          background: radial-gradient(
            circle,
            rgba(255, 255, 255, 0.8) 0%,
            rgba(255, 255, 255, 0) 70%
          );
          transform: translate(-50%, -50%) scale(0);
          opacity: 0.5;
          transition: all 0.5s ease;
          pointer-events: none;
        }
      }
    }
  }
}

.celebration {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
  background-color: rgba(0, 0, 0, 0.7);
  animation: fadeIn 0.5s ease-out;

  .confetti-container {
    position: absolute;
    width: 100%;
    height: 100%;
    overflow: hidden;
    pointer-events: none;
  }

  .confetti {
    position: absolute;
    width: 10px;
    height: 10px;
    background: linear-gradient(135deg, #ffd700 0%, #ffcc00 100%);
    border-radius: 2px;

    @for $i from 1 through 50 {
      &:nth-child(#{$i}) {
        top: -20px;
        left: percentage(random(100) / 100);
        opacity: random(10) / 10;
        transform: rotate(random(360) + deg);
        animation: confetti-fall #{random(5) + 2}s ease-in-out infinite;
        animation-delay: #{random(3)}s;
        width: #{random(10) + 5}px;
        height: #{random(10) + 5}px;

        @if $i % 3 == 0 {
          background: linear-gradient(135deg, #ffd700 0%, #ffcc00 100%);
        } @else if $i % 3 == 1 {
          background: linear-gradient(135deg, #e0e0e0 0%, #c0c0c0 100%);
        } @else {
          background: linear-gradient(135deg, #cd7f32 0%, #a05a2c 100%);
        }
      }
    }
  }

  .result-popup {
    background: white;
    padding: 30px;
    border-radius: 10px;
    text-align: center;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
    animation: popIn 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
    position: relative;
    z-index: 2;

    .result-icon {
      width: 80px;
      height: 80px;
      background: linear-gradient(135deg, #ffd700 0%, #ffcc00 100%);
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 0 auto 20px;
      box-shadow: 0 5px 15px rgba(255, 215, 0, 0.3);
      animation: pulse 2s infinite;

      .el-icon {
        font-size: 40px;
        color: white;
      }
    }

    h2 {
      font-size: 24px;
      margin: 0 0 10px;
      color: #303133;
    }

    p {
      color: #606266;
      margin: 0;
    }
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
    box-shadow: 0 0 15px rgba(242, 201, 76, 0.5);
  }
  50% {
    transform: scale(1.05);
    box-shadow: 0 0 20px rgba(242, 201, 76, 0.7);
  }
  100% {
    transform: scale(1);
    box-shadow: 0 0 15px rgba(242, 201, 76, 0.5);
  }
}

@keyframes confetti-fall {
  0% {
    transform: translateY(0) rotate(0deg);
    opacity: 1;
  }
  100% {
    transform: translateY(1000px) rotate(720deg);
    opacity: 0;
  }
}

@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

@keyframes popIn {
  0% {
    transform: scale(0.5);
    opacity: 0;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}
</style>
